import Food from './Food';
import Score from './Score';
import Snake from './Snake';
class GameControl {
    food: Food;
    snake: Snake;
    score: Score;
    constructor(public direction: string = '', public isLive: boolean = true){
        this.food = new Food();
        this.snake = new Snake();
        this.score = new Score();
        this.init()
    }
    // 游戏初始化
    init(){
        document.addEventListener('keydown',this.keydownHandler.bind(this))
        this.move()
    }
    // 键盘按下事件
    keydownHandler(event: KeyboardEvent){
        this.direction = event.key
      
    }
    move(){
        let X = this.snake.location.x;
        let Y = this.snake.location.y;
        switch(this.direction){
            case 'ArrowUp':
            case 'Up':
                Y -= 10
                break;
            case 'ArrowDown':
            case 'Down':
                Y += 10;
                break;
            case 'ArrowLeft':
            case 'Left':
                X -= 10;
                break;
            case 'ArrowRight':
            case 'Right':
                X += 10;
                break;
            default:
                break;
        }
        try {
            this.snake.X = X;
            this.snake.Y = Y;
        } catch (error:any) {
            alert(error.message + ' GAME OVER!')
            this.isLive = false;
        }
        if(this.checkEat(X,Y)){
            this.food.change()
            this.score.addScore()
            this.snake.addBody()
        }
       
        this.isLive && setTimeout(this.move.bind(this),300 - (this.score.level - 1) * 30)
    }
     checkEat(X:number,Y:number):boolean{
        if(X === this.food.X && Y === this.food.Y){
            return true
        }else{
            return false
        }
     }
}
export default GameControl;